<?php

namespace App\Http\Middleware;

ini_set('memory_limit', '512M');
set_time_limit(120);

use Closure;
use Illuminate\Http\Request;
use Rap2hpoutre\FastExcel\FastExcel;

class VerifyImportExcel
{
    /**
     * 检查上传的 Excel 是否符合要求，并解析 excel 内容.
     *
     * @param Request $request
     * @param Closure $next
     *
     * @return mixed
     *
     */
    public function handle(Request $request, Closure $next)
    {
        $file = $request->file('file');

        if (!$file || !$file->isValid()) {
            throw new \InvalidArgumentException('请上传文件');
        }
        // 文件类型验证
        if (!in_array($file->getClientOriginalExtension(), ['xlsx', 'xls', 'csv'])) {
            throw new \InvalidArgumentException('请上传Excel文件');
        }

        // mime type Excel 有时候会为application/zip
        //if ('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' != $file->getMimeType()) {
        //    throw new \InvalidArgumentException('请上传Excel文件');
        //}

        try {
            $lines = (new FastExcel())->importSheets($file->getPathname());
            if ($lines->count() === 1) {
                $lines = collect($lines->first());
            }
        } catch (\Throwable $t) {
            throw new \InvalidArgumentException('上传Excel文件存在问题');
        }

        if ($lines->isEmpty()) {
            throw new \InvalidArgumentException('上传的Excel文件为空, 请检查');
        }

        app()->instance('excel.lines', $lines);

        return $next($request);
    }
}
